<template>
  <div class="edit-internal-production-container">
    <el-container>
      <el-header class="form-header">
        <div class="page-title">
          <el-button 
            :icon="ArrowLeft" 
            @click="goBack" 
            circle 
            style="margin-right: 15px;"
          />
          编辑内部生产
        </div>
        <!-- 移动操作按钮到header -->
        <div class="header-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">更新</el-button>
        </div>
      </el-header>
      
      <el-main class="form-main" v-loading="loading">
        <div class="form-container">
          <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            label-width="120px"
            class="production-form"
          >
            <!-- 基础信息 -->
            <div class="form-section">
              <div class="section-title">基础信息</div>
              <div class="form-content">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="生产主题" prop="productionSubject">
                      <el-input v-model="formData.productionSubject" placeholder="请输入生产主题" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="生产类型" prop="productionType">
                      <el-select v-model="formData.productionType" placeholder="请选择生产类型" style="width: 100%">
                        <el-option label="批量生产" value="批量生产" />
                        <el-option label="定制生产" value="定制生产" />
                        <el-option label="试验生产" value="试验生产" />
                        <el-option label="紧急生产" value="紧急生产" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="生产单号" prop="productionOrderNo">
                      <el-input v-model="formData.productionOrderNo" placeholder="生产单号" readonly />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="截止日期" prop="documentDate">
                      <el-date-picker
                        v-model="formData.documentDate"
                        type="date"
                        placeholder="请选择截止日期"
                        style="width: 100%"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="销售订单" prop="salesOrderHold">
                      <el-input 
                        :value="formData.salesOrderHold > 0 ? `销售订单ID: ${formData.salesOrderHold}` : ''"
                        :placeholder="noSalesOrder ? '不指定销售订单' : '请选择销售订单'" 
                        :readonly="true"
                        :disabled="noSalesOrder"
                        @click="!noSalesOrder && openSalesOrderDialog()"
                      >
                        <template #append>
                          <el-button 
                            :icon="Search" 
                            :disabled="noSalesOrder"
                            @click="openSalesOrderDialog"
                          ></el-button>
                        </template>
                      </el-input>
                      <el-checkbox 
                        v-model="noSalesOrder" 
                        @change="handleNoSalesOrderChange"
                        style="margin-top: 8px;"
                      >
                        不指定销售订单
                      </el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="关联项目">
                      <el-input v-model="formData.associatedProject" placeholder="请输入关联项目" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="发起部门">
                      <el-input v-model="formData.initiatingDepartment" placeholder="请输入发起部门" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="负责人" prop="responsiblePerson">
                      <el-input v-model="formData.responsiblePerson" placeholder="请输入负责人" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="联系电话">
                      <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="生产部门">
                      <el-input v-model="formData.productionDepartment" placeholder="请输入生产部门" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="生产人员">
                      <el-input v-model="formData.productionPersonnel" placeholder="请输入生产人员" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="备注">
                      <el-input
                        v-model="formData.remarks"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入备注信息"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>

            <!-- 生产产品 -->
            <div class="form-section">
              <div class="section-title">生产产品</div>
              <div class="form-content">
                <div class="table-operations">
                  <el-button type="primary" :icon="Plus" @click="addProductItem">添加生产物品</el-button>
                  <el-button type="danger" :icon="Delete" @click="deleteSelectedProducts">删除选中</el-button>
                </div>
                <el-table
                  :data="formData.productItems"
                  class="form-table"
                  @selection-change="handleProductSelectionChange"
                  :border="true"
                  :stripe="true"
                >
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column type="index" label="序号" width="80" align="center" />
                  <el-table-column prop="itemCode" label="物品编号" width="140" align="center" />
                  <el-table-column prop="itemName" label="物品名称" min-width="150" />
                  <el-table-column prop="specification" label="规格型号" width="120" align="center" />
                  <el-table-column prop="unit" label="单位" width="80" align="center" />
                  <el-table-column prop="materialType" label="物料类型" width="100" align="center" />
                  <el-table-column prop="brand" label="品牌" width="100" />
                  <el-table-column prop="category" label="物品分类" width="100" align="center" />
                  <el-table-column label="计划生产数量" width="130" align="center">
                    <template #default="scope">
                      <el-input-number
                        v-model="scope.row.plannedQuantity"
                        :min="0"
                        :precision="2"
                        size="small"
                        style="width: 100%"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" min-width="150">
                    <template #default="scope">
                      <el-input
                        v-model="scope.row.remark"
                        placeholder="请输入备注"
                        size="small"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="100" align="center">
                    <template #default="scope">
                      <el-button
                        link
                        type="danger"
                        @click="deleteProductItem(scope.$index)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div v-if="formData.productItems.length === 0" class="empty-table">
                  暂无生产产品数据
                </div>
              </div>
            </div>

            <!-- 消耗物品 -->
            <div class="form-section">
              <div class="section-title">消耗物品</div>
              <div class="form-content">
                <div class="table-operations">
                  <el-button type="primary" :icon="Plus" @click="addConsumableItem">添加消耗物品</el-button>
                  <el-button type="danger" :icon="Delete" @click="deleteSelectedConsumables">删除选中</el-button>
                </div>
                <el-table
                  :data="formData.consumableItems"
                  class="form-table"
                  @selection-change="handleConsumableSelectionChange"
                  :border="true"
                  :stripe="true"
                >
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column type="index" label="序号" width="80" align="center" />
                  <el-table-column prop="itemCode" label="物品编号" width="140" align="center" />
                  <el-table-column prop="itemName" label="物品名称" min-width="150" />
                  <el-table-column prop="specification" label="规格型号" width="120" align="center" />
                  <el-table-column prop="unit" label="单位" width="80" align="center" />
                  <el-table-column prop="materialType" label="物料类型" width="100" align="center" />
                  <el-table-column prop="brand" label="品牌" width="100" />
                  <el-table-column prop="category" label="物品分类" width="100" align="center" />
                  <el-table-column prop="warehouseName" label="仓库名称" width="120" />
                  <el-table-column label="计划数量" width="110" align="center">
                    <template #default="scope">
                      <el-input-number
                        v-model="scope.row.plannedQuantity"
                        :min="0"
                        :precision="2"
                        size="small"
                        style="width: 100%"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="number" label="编号" width="100" />
                  <el-table-column label="备注" min-width="150">
                    <template #default="scope">
                      <el-input
                        v-model="scope.row.remark"
                        placeholder="请输入备注"
                        size="small"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="100" align="center">
                    <template #default="scope">
                      <el-button
                        link
                        type="danger"
                        @click="deleteConsumableItem(scope.$index)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div v-if="formData.consumableItems.length === 0" class="empty-table">
                  暂无消耗物品数据
                </div>
              </div>
            </div>

            <!-- 附件上传 -->
            <div class="form-section">
              <div class="section-title">附件</div>
              <div class="form-content">
                <div class="attachment-section">
                  <div class="attachment-left">
                    <div class="uploaded-files" v-if="formData.attachments.length > 0">
                      <div class="files-title">已上传文件 ({{ formData.attachments.length }})</div>
                      <div class="file-list">
                        <div 
                          v-for="(file, index) in formData.attachments" 
                          :key="index" 
                          class="file-item"
                        >
                          <el-icon><Document /></el-icon>
                          <span class="file-name">{{ file.filename || file.name }}</span>
                          <span class="file-size">({{ formatFileSize(file.filesize || file.size || 0) }})</span>
                          <span class="upload-time">{{ formatTime(file.uploadTime || new Date()) }}</span>
                          <el-button 
                            link 
                            type="danger" 
                            @click="removeFile(index)"
                            style="margin-left: 10px;"
                          >
                            删除
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="attachment-right">
                    <el-upload
                      class="upload-area"
                      drag
                      :action="''"
                      multiple
                      :auto-upload="false"
                      :on-change="handleFileSelect"
                      :show-file-list="false"
                      :accept="'.pdf,.doc,.docx,.xls,.xlsx,.png,.jpg,.jpeg,.txt'">
                      <div class="upload-content">
                        <el-icon class="upload-icon"><UploadFilled /></el-icon>
                        <div>点击上传 / 拖拽到此区域</div>
                        <div class="upload-hint">支持 PDF、Word、Excel、图片等格式</div>
                        <div class="upload-buttons">
                          <el-button type="primary" size="small" @click="handleBatchUpload">批量上传</el-button>
                        </div>
                      </div>
                    </el-upload>
                  </div>
                </div>
              </div>
            </div>
          </el-form>
        </div>
      </el-main>
    </el-container>

    <!-- 物品选择对话框 -->
    <el-dialog
      v-model="itemDialogVisible"
      :title="itemDialogTitle"
      width="1200px"
      :close-on-click-modal="false"
    >
      <div class="item-search">
        <el-form :inline="true" :model="itemSearch" class="item-search-form">
          <el-form-item label="物品编码">
            <el-input v-model="itemSearch.itemCode" placeholder="请输入物品编码" style="width: 150px" />
          </el-form-item>
          <el-form-item label="物品名称">
            <el-input v-model="itemSearch.itemName" placeholder="请输入物品名称" style="width: 150px" />
          </el-form-item>
          <el-form-item label="物料类型">
            <el-select v-model="itemSearch.materialType" placeholder="请选择" style="width: 120px">
              <el-option label="原材料" value="原材料" />
              <el-option label="半成品" value="半成品" />
              <el-option label="成品" value="成品" />
            </el-select>
          </el-form-item>
          <el-form-item label="物品分类">
            <el-select v-model="itemSearch.category" placeholder="请选择" style="width: 150px">
              <el-option
                v-for="category in categoryList"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchItems">搜索</el-button>
            <el-button @click="resetItemSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        :data="itemList"
        @selection-change="handleItemSelectionChange"
        v-loading="itemLoading"
        :border="true"
        :stripe="true"
        max-height="400"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="itemCode" label="物品编码" width="120" />
        <el-table-column prop="itemName" label="物品名称" min-width="150" />
        <el-table-column prop="specification" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column prop="materialType" label="物料类型" width="100" />
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="inventory" label="库存" width="80" align="center" />
      </el-table>

      <div class="dialog-pagination">
        <el-pagination
          v-model:current-page="itemPagination.pageIndex"
          v-model:page-size="itemPagination.pageSize"
          :page-sizes="[5, 10, 20]"
          :background="true"
          layout="sizes, prev, pager, next, jumper"
          :total="itemTotal"
          @size-change="handleItemSizeChange"
          @current-change="handleItemCurrentChange"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="itemDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectItems">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 销售订单选择对话框 -->
    <el-dialog
      v-model="salesOrderDialogVisible"
      title="选择销售订单"
      width="80%"
      :before-close="() => salesOrderDialogVisible = false"
    >
      <!-- 搜索区域 -->
      <div style="margin-bottom: 16px;">
        <el-row :gutter="16">
          <el-col :span="5">
            <el-input 
              v-model="salesOrderSearch.orderNumber" 
              placeholder="请输入销售单号/主题"
              clearable
            />
          </el-col>
          <el-col :span="5">
            <el-input 
              v-model="salesOrderSearch.customerName" 
              placeholder="请输入客户名称"
              clearable
            />
          </el-col>
          <el-col :span="5">
            <el-date-picker
              v-model="salesOrderSearch.orderDate"
              type="date"
              placeholder="请选择销售日期"
              style="width: 100%"
              clearable
            />
          </el-col>
          <el-col :span="5">
            <el-select 
              v-model="salesOrderSearch.status" 
              placeholder="请选择订单状态"
              style="width: 100%"
              clearable
            >
              <el-option label="生产中" value="生产中" />
              <el-option label="已完成" value="已完成" />
              <el-option label="未开始" value="未开始" />
              <el-option label="已取消" value="已取消" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="searchSalesOrders">查询</el-button>
            <el-button @click="resetSalesOrderSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 表格区域 -->
      <el-table 
        :data="salesOrderList" 
        stripe 
        border 
        style="width: 100%"
        v-loading="salesOrderLoading"
        @selection-change="handleSalesOrderSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="orderNo" label="销售单号" width="140" align="center" />
        <el-table-column prop="subject" label="销售订单主题" min-width="180" />
        <el-table-column prop="customerName" label="客户名称" min-width="160" />
        <el-table-column prop="orderDate" label="销售日期" width="120" align="center" />
        <el-table-column prop="status" label="订单状态" width="100" align="center" />
        <el-table-column prop="details" label="物品概要" width="140" align="center" />
      </el-table>

      <!-- 分页区域 -->
      <div style="margin-top: 16px; display: flex; justify-content: space-between; align-items: center;">
        <span>共 {{ salesOrderTotal }} 条数据</span>
        <el-pagination
          v-model:current-page="salesOrderPagination.pageIndex"
          v-model:page-size="salesOrderPagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="salesOrderTotal"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleSalesOrderSizeChange"
          @current-change="handleSalesOrderCurrentChange"
        />
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="salesOrderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectSalesOrder">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadFile } from 'element-plus'
import { Plus, Delete, Document, UploadFilled, ArrowLeft, Search } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import { 
  updateInternalProduction, 
  getInternalProductionDetailById,
  uploadFile as apiUploadFile,
  getItemCategoryTree,
  getItems,
  getItemss,
  getSalesOrderItems,
  getSalesOrders
} from '@/Https/server'

const router = useRouter()
const route = useRoute()

// 获取路由参数中的生产ID
const productionId = ref(route.params.id as string)

// 页面加载状态
const loading = ref(false)
// 提交状态
const submitting = ref(false)

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
  id: 0,
  productionSubject: '',
  productionType: '',
  productionOrderNo: '',
  salesOrderHold: 0,
  documentDate: '',
  associatedProject: '',
  initiatingDepartment: '',
  responsiblePerson: '',
  contactPhone: '',
  productionDepartment: '',
  productionPersonnel: '',
  remarks: '',
  modifierName: '',
  productItems: [] as any[],
  consumableItems: [] as any[],
  attachments: [] as any[]
})

// 表单验证规则
const formRules = {
  productionSubject: [
    { required: true, message: '请输入生产主题', trigger: 'blur' }
  ],
  productionType: [
    { required: true, message: '请选择生产类型', trigger: 'change' }
  ],
  productionOrderNo: [
    { required: true, message: '请输入生产单号', trigger: 'blur' }
  ],
  documentDate: [
    { required: true, message: '请选择截止日期', trigger: 'change' }
  ],
  responsiblePerson: [
    { required: true, message: '请输入负责人', trigger: 'blur' }
  ]
}

// 选中的生产物品和消耗物品
const selectedProducts = ref<any[]>([])
const selectedConsumables = ref<any[]>([])

// 物品选择对话框相关
const itemDialogVisible = ref(false)
const itemDialogTitle = ref('')
const currentItemType = ref('') // 'product' 或 'consumable'
const itemLoading = ref(false)
const itemList = ref<any[]>([])
const selectedItems = ref<any[]>([])
const itemTotal = ref(0)

// 物品搜索条件
const itemSearch = reactive({
  itemCode: '',
  itemName: '',
  materialType: '',
  category: ''
})

// 销售订单相关状态
const noSalesOrder = ref(false)
const salesOrderDialogVisible = ref(false)
const salesOrderLoading = ref(false)
const salesOrderList = ref<any[]>([])
const selectedSalesOrder = ref<any>(null)
const salesOrderTotal = ref(0)

// 销售订单搜索条件
const salesOrderSearch = reactive({
  orderNumber: '',
  customerName: '',
  orderDate: '',
  status: ''
})

// 销售订单分页
const salesOrderPagination = reactive({
  pageIndex: 1,
  pageSize: 5
})

// 物品分页
const itemPagination = reactive({
  pageIndex: 1,
  pageSize: 5
})

// 物品分类列表
const categoryList = ref<any[]>([])

// 根据分类ID获取分类名称
const getClassificationName = (classificationId: number): string => {
  const classificationMap: { [key: number]: string } = {
    1: '原材料',  // 根据API数据，ID为1对应原材料
    2: '半成品', 
    3: '成品',
    4: '物料',
    5: '家具',
    6: '电子产品',
    7: '衣物',
    8: '食品',
    9: '化妆品'
  }
  return classificationMap[classificationId] || ''
}

onMounted(() => {
  if (productionId.value) {
    loadProductionDetail()
  } else {
    ElMessage.error('内部生产ID参数缺失')
  }
  loadCategoryList()
})

// 加载内部生产详情数据
const loadProductionDetail = async () => {
  if (!productionId.value || safeNumber(productionId.value) <= 0) {
    ElMessage.error('内部生产ID无效')
    return
  }
  
  try {
    loading.value = true
    
    const response: any = await getInternalProductionDetailById({ productionId: productionId.value })
    
    if (response && response.code === 200 && response.data) {
      const data = response.data
      
      // 尝试多种可能的数据结构
      const productionInfo = data.productionInfo || data.internalProduction || data
      
      // 回显基础信息 - 尝试多种字段名（包括大写开头）
      formData.id = Number(productionId.value)
      formData.productionSubject = productionInfo.productionSubject || productionInfo.ProductionSubject || productionInfo.subject || productionInfo.Subject || productionInfo.title || productionInfo.Title || ''
      formData.productionType = productionInfo.productionType || productionInfo.ProductionType || productionInfo.type || productionInfo.Type || ''
      formData.productionOrderNo = productionInfo.productionOrderNo || productionInfo.ProductionOrderNo || productionInfo.orderNo || productionInfo.OrderNo || productionInfo.number || productionInfo.Number || ''
      formData.salesOrderHold = safeNumber(productionInfo.salesOrderHold || productionInfo.SalesOrderHold || productionInfo.salesOrderNoId || productionInfo.SalesOrderNoId || productionInfo.salesOrder || productionInfo.SalesOrder || 0)
      // 设置销售订单选择状态
      noSalesOrder.value = formData.salesOrderHold === 0
      formData.documentDate = formatDateForInput(productionInfo.documentDate || productionInfo.DocumentDate || productionInfo.deadline || productionInfo.Deadline || productionInfo.date || productionInfo.Date)
      formData.associatedProject = productionInfo.associatedProject || productionInfo.AssociatedProject || productionInfo.project || productionInfo.Project || ''
      formData.initiatingDepartment = productionInfo.initiatingDepartment || productionInfo.InitiatingDepartment || productionInfo.department || productionInfo.Department || ''
      formData.responsiblePerson = productionInfo.responsiblePerson || productionInfo.ResponsiblePerson || productionInfo.responsible || productionInfo.Responsible || ''
      formData.contactPhone = productionInfo.contactPhone || productionInfo.ContactPhone || productionInfo.phone || productionInfo.Phone || ''
      formData.productionDepartment = productionInfo.productionDepartment || productionInfo.ProductionDepartment || productionInfo.prodDept || productionInfo.ProdDept || ''
      formData.productionPersonnel = productionInfo.productionPersonnel || productionInfo.ProductionPersonnel || productionInfo.personnel || productionInfo.Personnel || ''
      formData.remarks = productionInfo.remarks || productionInfo.Remarks || productionInfo.remark || productionInfo.Remark || productionInfo.note || productionInfo.Note || ''
      formData.modifierName = '当前用户' // 设置修改人
      
      // 回显生产产品 - 尝试多种字段名（包括大写开头）
      const productionItemsData = data.productionItems || data.productItems || data.products || data.items || 
                                   data.ProductionItems || data.ProductItems || data.Products || data.Items || []
      if (Array.isArray(productionItemsData) && productionItemsData.length > 0) {
          formData.productItems = productionItemsData.map((item: any) => ({
              id: safeNumber(item.id || item.Id),
              goodsId: safeNumber(item.goodsId || item.GoodsId || item.itemId || item.ItemId || item.id || item.Id),
              itemCode: safeString(item.itemCode || item.ItemCode || item.code || item.Code),
              itemName: safeString(item.itemName || item.ItemName || item.name || item.Name || item.productName || item.ProductName),
              specification: safeString(item.specification || item.Specification || item.spec || item.Spec),
              unit: safeString(item.unit || item.Unit || item.unitName || item.UnitName),
              brand: safeString(item.brand || item.Brand),
              materialType: safeString(item.materialType || item.MaterialType || item.itemType || item.ItemType),
              category: getClassificationName(item.itemclassificationId || item.itemClassificationId || item.ItemClassificationId || item.classificationId || item.ClassificationId) || safeString(item.categoryName || item.CategoryName),
              inventory: safeNumber(item.totalInventory || item.TotalInventory || item.totalinventory || item.inventory || item.Inventory),
              plannedQuantity: safeNumber(item.plannedProduction || item.PlannedProduction || item.plannedQuantity || item.PlannedQuantity || item.quantity || item.Quantity || item.amount || item.Amount),
              remark: safeString(item.remark || item.Remark || item.remarks || item.Remarks || item.note || item.Note)
          }))
      } else {
        formData.productItems = []
      }
      
      // 回显消耗物品 - 尝试多种字段名（包括大写开头）
      const consumableItemsData = data.consumableItems || data.consumables || data.materials || data.rawMaterials || 
                                   data.ConsumableItems || data.Consumables || data.Materials || data.RawMaterials || []
      if (Array.isArray(consumableItemsData) && consumableItemsData.length > 0) {
          formData.consumableItems = consumableItemsData.map((item: any) => ({
              id: safeNumber(item.id || item.Id),
              goodsId: safeNumber(item.goodsId || item.GoodsId || item.itemId || item.ItemId || item.id || item.Id),
              itemCode: safeString(item.itemCode || item.ItemCode || item.code || item.Code),
              itemName: safeString(item.itemName || item.ItemName || item.name || item.Name || item.materialName || item.MaterialName),
              specification: safeString(item.specification || item.Specification || item.spec || item.Spec),
              warehouseId: safeNumber(item.warehouseId || item.WarehouseId || item.warehouseID || item.WarehouseID),
              unit: safeString(item.unit || item.Unit || item.unitName || item.UnitName),
              brand: safeString(item.brand || item.Brand),
              materialType: safeString(item.materialType || item.MaterialType || item.itemType || item.ItemType),
              category: getClassificationName(item.itemclassificationId || item.itemClassificationId || item.ItemClassificationId || item.classificationId || item.ClassificationId) || safeString(item.categoryName || item.CategoryName),
              inventory: safeNumber(item.totalInventory || item.TotalInventory || item.totalinventory || item.inventory || item.Inventory),
              warehouseName: safeString(item.warehouseName || item.WarehouseName || item.warehouse || item.Warehouse),
              plannedQuantity: safeNumber(item.plannedQuantity || item.PlannedQuantity || item.plannedConsumption || item.PlannedConsumption || item.quantity || item.Quantity || item.amount || item.Amount),
              number: safeString(item.number || item.Number || item.sequenceNumber || item.SequenceNumber),
              remark: safeString(item.remark || item.Remark || item.remarks || item.Remarks || item.note || item.Note)
          }))
      } else {
        formData.consumableItems = []
      }
      
      // 回显附件 - 尝试多种字段名（包括大写开头）
      const attachmentsData = data.attachments || data.Attachments || []
      if (Array.isArray(attachmentsData)) {
        formData.attachments = attachmentsData.map((file: any) => ({
          id: safeNumber(file.id || file.Id),
          filename: safeString(file.filename || file.Filename || file.fileName || file.FileName || file.name || file.Name),
          filepath: safeString(file.filepath || file.Filepath || file.filePath || file.FilePath || file.url || file.Url),
          filesize: safeNumber(file.filesize || file.Filesize || file.fileSize || file.FileSize || file.size || file.Size),
          uploadTime: file.uploadtime || file.uploadTime || file.UploadTime || new Date()
        }))
      }
    } else {
      ElMessage.error(response?.message || '获取内部生产详情失败')
    }
  } catch (error: any) {
    console.error('获取内部生产详情失败:', error)
    ElMessage.error(error?.message || '获取内部生产详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 格式化日期为输入框格式
const formatDateForInput = (dateStr: string | null | undefined) => {
  if (!dateStr) return ''
  try {
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) {
      console.warn('无效日期格式:', dateStr)
      return ''
    }
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  } catch (error) {
    console.error('日期格式化错误:', error, '原始值:', dateStr)
    return ''
  }
}

// 安全的数字转换函数
const safeNumber = (value: any, defaultValue: number = 0): number => {
  if (value === null || value === undefined || value === '') return defaultValue
  const num = Number(value)
  return isNaN(num) ? defaultValue : num
}

// 安全的字符串转换函数
const safeString = (value: any, defaultValue: string = ''): string => {
  if (value === null || value === undefined) return defaultValue
  return String(value)
}

// 格式化日期为ISO格式
const formatDateForISO = (dateStr: string | null | undefined): string | null => {
  if (!dateStr) return null
  try {
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) {
      console.warn('无效日期格式:', dateStr)
      return null
    }
    return date.toISOString()
  } catch (error) {
    console.error('日期ISO格式化错误:', error, '原始值:', dateStr)
    return null
  }
}

// 加载物品分类
const loadCategoryList = async () => {
  try {
    const response: any = await getItemCategoryTree()
    if (response && response.code === 200 && response.data) {
      categoryList.value = response.data
    }
  } catch (error) {
    console.error('加载物品分类失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        submitting.value = true
        
        // 构建提交数据，严格按照后端API要求的格式
        const submitData = {
          id: safeNumber(formData.id),
          ProductionSubject: safeString(formData.productionSubject),
          ProductionType: safeString(formData.productionType),
          ProductionOrderNo: safeString(formData.productionOrderNo),
          SalesOrderNoId: formData.salesOrderHold && formData.salesOrderHold > 0 ? safeNumber(formData.salesOrderHold) : null,
          DocumentDate: formData.documentDate ? formatDateForISO(formData.documentDate) : null,
          AssociatedProject: safeString(formData.associatedProject),
          InitiatingDepartment: safeString(formData.initiatingDepartment),
          ResponsiblePerson: safeString(formData.responsiblePerson),
          ContactPhone: safeString(formData.contactPhone),
          ProductionDepartment: safeString(formData.productionDepartment),
          ProductionPersonnel: safeString(formData.productionPersonnel),
          Remarks: safeString(formData.remarks),
          ModifierName: safeString(formData.modifierName, '当前用户'),
          ProductionItems: formData.productItems.map(item => ({
            id: safeNumber(item.id),
            GoodsId: safeNumber(item.goodsId || item.id),
            Plannedproduction: safeNumber(item.plannedQuantity),
            Remark: safeString(item.remark)
          })),
          ConsumableItems: formData.consumableItems.map(item => ({
            id: safeNumber(item.id),
            GoodsId: safeNumber(item.goodsId || item.id),
            WarehouseId: item.warehouseId ? safeNumber(item.warehouseId) : null,
            Plannedquantity: safeNumber(item.plannedQuantity),
            Number: safeNumber(item.quantity),
            Remark: safeString(item.remark)
          })),
          Attachments: formData.attachments.map(attachment => ({
            id: safeNumber(attachment.id),
            Filename: safeString(attachment.filename || attachment.name),
            Filepath: safeString(attachment.filepath || attachment.url),
            Filesize: safeNumber(attachment.filesize || attachment.size)
          }))
        }
        
        // 调用更新API
        const response = await updateInternalProduction(submitData)
        
        let responseData: any = response
        if (response && typeof response === 'object' && 'data' in response) {
          responseData = (response as any).data
        }
        
        if (responseData && typeof responseData === 'object' && responseData.code === 200) {
          ElMessage.success('内部生产信息更新成功！')
          router.push('/ShowInternalProduction')
        } else if (responseData && typeof responseData === 'object' && responseData.code === 500) {
          ElMessage.error(`更新失败: ${responseData.message || '服务器内部错误'}`)
        } else if (responseData && typeof responseData === 'object' && responseData.code === 400) {
          ElMessage.error(`参数错误: ${responseData.message || '请求参数有误'}`)
        } else {
          ElMessage.success('内部生产信息更新成功！')
          router.push('/ShowInternalProduction')
        }
      } catch (error: any) {
        console.error('更新内部生产失败:', error)
        ElMessage.error(error?.message || '更新失败，请稍后重试')
      } finally {
        submitting.value = false
      }
    } else {
      ElMessage.error('请完善必填信息')
    }
  })
}

// 取消编辑
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消编辑吗？未保存的更改将丢失。', '确认取消', {
    type: 'warning'
  }).then(() => {
    router.back()
  })
}

// 返回
const goBack = () => {
  router.back()
}

// 添加生产物品
const addProductItem = () => {
  currentItemType.value = 'product'
  itemDialogTitle.value = '选择生产物品'
  itemDialogVisible.value = true
  resetItemSearch()
  loadItems()
}

// 添加消耗物品
const addConsumableItem = () => {
  currentItemType.value = 'consumable'
  itemDialogTitle.value = '选择消耗物品'
  itemDialogVisible.value = true
  resetItemSearch()
  loadItems()
}

// 加载物品列表
const loadItems = async () => {
  itemLoading.value = true
  try {
    // 构建查询参数
    const params: any = {
      PageIndex: itemPagination.pageIndex,
      PageSize: itemPagination.pageSize,
    }

    // 根据当前物品类型选择不同的API和参数
    if (currentItemType.value === 'product') {
      // 生产物品：使用销售订单物品API
      if (formData.salesOrderHold && parseInt(formData.salesOrderHold.toString()) > 0) {
        // 确保传递的是数字类型的ID
        params.SalesOrderId = parseInt(formData.salesOrderHold.toString())
      }
      
      if (itemSearch.itemCode || itemSearch.itemName) {
        params.SearchKeyword = itemSearch.itemCode || itemSearch.itemName
      }
      
      if (itemSearch.materialType) {
        params.ItemType = itemSearch.materialType
      }
      
      if (itemSearch.category) {
        params.ItemclassificationId = parseInt(itemSearch.category)
      }

      // 使用销售订单物品API
      const response: any = await getSalesOrderItems(params)
      
      if (response) {
        const data = response
        
        // 处理返回的数据，映射到前端需要的格式
        itemList.value = data.pageData?.map((item: any) => ({
          // 基础显示字段 - 对应图二显示要求
          itemCode: item.itemCode || item.ItemCode || item.code || item.Code || '',
          itemName: item.itemName || item.ItemName || item.name || item.Name || '',
          specification: item.specification || item.Specification || item.spec || item.Spec || '',
          unit: item.unit || item.Unit || item.unitName || item.UnitName || '',
          materialType: item.itemType || item.materialType || item.ItemType || '',  // 物料类型
          category: getClassificationName(item.itemclassificationId || item.itemClassificationId || item.classificationId) || '', // 物品分类
          inventory: item.totalInventory || item.totalinventory || item.inventory || 0, // 库存
          // 后端需要的核心字段
          id: item.id,
          goodsId: item.id, // 用于后端提交
          // 从API获取的数据
          quantity: item.number || item.quantity || 1, // 从API获取数量
          plannedQuantity: item.planQuantity || item.plannedQuantity || item.number || 1, // 从API获取计划数量
          deliveryDate: item.itemexpiration ? new Date(item.itemexpiration).toISOString().split('T')[0] : (item.deliveryDate || item.expectedDate || ''), // 从API获取交付日期并格式化
          // 保留原始数据以备后用
          rowNumber: item.rowNumber,
          salePrice: item.salePrice,
          brand: item.brand,
          manufacturerModel: item.manufacturerModel,
          upper: item.upper,
          number: item.number,
          itemsImg: item.itemsImg,
          auxiliaryUnits: item.auxiliaryUnits,
          itemsRemark: item.itemsRemark,
          createTime: item.createTime,
          modifyTime: item.modifyTime,
          createName: item.createName,
          modifierName: item.modifierName,
          salesOrderId: item.salesOrderId,
          relationId: item.relationId,
          hasStock: item.hasStock,
          isExpiringSoon: item.isExpiringSoon,
          isExpired: item.isExpired,
          stockStatus: item.stockStatus,
          priceRange: item.priceRange,
          expirationStatus: item.expirationStatus,
          daysToExpiration: item.daysToExpiration
        })) || []
        
        itemTotal.value = data.totalCount || 0
      } else {
        ElMessage.error('加载生产物品数据失败：响应数据格式错误')
        itemList.value = []
        itemTotal.value = 0
      }
    } else {
      // 消耗物品：使用物品列表API
      if (itemSearch.itemCode || itemSearch.itemName) {
        params.SearchKeyword = itemSearch.itemCode || itemSearch.itemName
      }
      
      if (itemSearch.materialType) {
        params.ItemType = itemSearch.materialType
      }
      
      if (itemSearch.category) {
        params.ItemclassificationId = parseInt(itemSearch.category)
      }

      // 使用物品列表API
      const response: any = await getItemss(params)
      
      if (response) {
        const data = response
        
        // 处理返回的数据，映射到前端需要的格式  
        itemList.value = data.pageData?.map((item: any) => ({
          // 基础显示字段 - 对应图二显示要求
          itemCode: item.itemCode || item.ItemCode || item.code || item.Code || '',
          itemName: item.itemName || item.ItemName || item.name || item.Name || '',
          specification: item.specification || item.Specification || item.spec || item.Spec || '',
          unit: item.unit || item.Unit || item.unitName || item.UnitName || '',
          materialType: item.itemType || item.materialType || item.ItemType || '',  // 物料类型
          category: getClassificationName(item.itemclassificationId || item.itemClassificationId || item.classificationId) || item.categoryName || '', // 物品分类
          inventory: item.totalInventory || item.totalinventory || item.inventory || 0, // 库存
          // 后端需要的核心字段
          id: item.id,
          goodsId: item.id, // 用于后端提交
          // 从API获取的数据
          quantity: item.quantity || item.number || 1, // 从API获取数量
          plannedQuantity: item.plannedQuantity || item.planQuantity || 1, // 从API获取计划消耗数量
          warehouseId: item.warehouseId || 0, // 仓库ID
          // 保留原始数据以备后用
          categoryName: item.categoryName,
          state: item.state,
          brand: item.brand,
          salePrice: item.salePrice,
          itemsRemark: item.itemsRemark
        })) || []
        
        itemTotal.value = data.totalCount || 0
      } else {
        ElMessage.error('加载消耗物品数据失败：响应数据格式错误')
        itemList.value = []
        itemTotal.value = 0
      }
    }
    
  } catch (apiError: any) {
    console.error('加载物品数据错误:', apiError)
    
    // 处理网络错误和服务器错误
    if (apiError.response) {
      const status = apiError.response.status
      ElMessage.error(`加载物品数据失败 (${status}): ${apiError.response.data?.message || '服务器错误'}`)
    } else if (apiError.request) {
      if (apiError.code === 'ECONNABORTED' || apiError.message.includes('timeout')) {
        ElMessage.error('加载物品数据超时，请检查网络连接后重试')
      } else {
        ElMessage.error('网络连接失败，请检查网络连接后重试')
      }
    } else {
      ElMessage.error(`加载物品数据失败: ${apiError.message}`)
    }
    
    itemList.value = []
    itemTotal.value = 0
  } finally {
    itemLoading.value = false
  }
}

// 搜索物品
const searchItems = () => {
  itemPagination.pageIndex = 1
  loadItems()
}

// 重置物品搜索
const resetItemSearch = () => {
  itemSearch.itemCode = ''
  itemSearch.itemName = ''
  itemSearch.materialType = ''
  itemSearch.category = ''
  itemPagination.pageIndex = 1
  loadItems()
}

// 处理物品选择变化
const handleItemSelectionChange = (selection: any[]) => {
  selectedItems.value = selection
}

// 处理物品分页大小变化
const handleItemSizeChange = (val: number) => {
  itemPagination.pageSize = val
  itemPagination.pageIndex = 1
  loadItems()
}

// 处理物品当前页变化
const handleItemCurrentChange = (val: number) => {
  itemPagination.pageIndex = val
  loadItems()
}

// 确认选择物品
const confirmSelectItems = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择至少一个物品')
    return
  }

  selectedItems.value.forEach(item => {
    const newItem = {
      id: 0, // 新增记录的ID为0，表示这是新记录
      goodsId: item.id, // 物品ID，用于后端提交
      itemCode: item.itemCode || item.ItemCode || item.code || item.Code || '',
      itemName: item.itemName || item.ItemName || item.name || item.Name || '',
      specification: item.specification || item.Specification || item.spec || item.Spec || '',
      unit: item.unit || item.Unit || item.unitName || item.UnitName || '',
      brand: item.brand || item.Brand || '',
      materialType: item.materialType, // 物料类型
      quantity: item.quantity || 1, // 从API获取的数量
      warehouseId: item.warehouseId || null, // 仓库ID，默认为空，用户选择
      warehouseName: item.warehouseName || '', // 仓库名称
      plannedQuantity: 1, // 计划数量默认为1，用户手动输入
      actualQuantity: 0, // 实际消耗数量，默认为0，用户手动输入
      deliveryDate: item.deliveryDate || '', // 从API获取的交付日期
      number: item.number || '', // 编号
      remark: '', // 备注默认为空
      inventory: item.inventory, // 库存
      category: item.category // 物品分类
    }

    if (currentItemType.value === 'product') {
      // 检查是否已存在（基于物品ID判断）
      const exists = formData.productItems.some(existingItem => existingItem.goodsId === item.id)
      if (!exists) {
        formData.productItems.push(newItem)
      }
    } else {
      // 检查是否已存在（基于物品ID判断）
      const exists = formData.consumableItems.some(existingItem => existingItem.goodsId === item.id)
      if (!exists) {
        formData.consumableItems.push(newItem)
      }
    }
  })

  itemDialogVisible.value = false
  ElMessage.success(`已添加 ${selectedItems.value.length} 个物品`)
}

// 删除生产物品
const deleteProductItem = (index: number) => {
  formData.productItems.splice(index, 1)
}

// 删除消耗物品
const deleteConsumableItem = (index: number) => {
  formData.consumableItems.splice(index, 1)
}

// 删除选中的生产物品
const deleteSelectedProducts = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要删除的物品')
    return
  }
  
  ElMessageBox.confirm('确定删除选中的生产物品吗？', '确认删除', {
    type: 'warning'
  }).then(() => {
    const selectedIds = selectedProducts.value.map(item => item.id)
    formData.productItems = formData.productItems.filter(item => !selectedIds.includes(item.id))
    ElMessage.success('删除成功')
  })
}

// 删除选中的消耗物品
const deleteSelectedConsumables = () => {
  if (selectedConsumables.value.length === 0) {
    ElMessage.warning('请选择要删除的物品')
    return
  }
  
  ElMessageBox.confirm('确定删除选中的消耗物品吗？', '确认删除', {
    type: 'warning'
  }).then(() => {
    const selectedIds = selectedConsumables.value.map(item => item.id)
    formData.consumableItems = formData.consumableItems.filter(item => !selectedIds.includes(item.id))
    ElMessage.success('删除成功')
  })
}

// 处理生产物品选择变化
const handleProductSelectionChange = (selection: any[]) => {
  selectedProducts.value = selection
}

// 处理消耗物品选择变化
const handleConsumableSelectionChange = (selection: any[]) => {
  selectedConsumables.value = selection
}

// 文件上传相关
const handleFileSelect = async (file: any) => {
  if (!file.raw) {
    console.error('文件对象无效:', file)
    return
  }
  
  // 检查文件大小限制 (50MB)
  const maxSize = 50 * 1024 * 1024
  if (file.raw.size > maxSize) {
    ElMessage.error(`文件 "${file.name}" 大小超过50MB限制`)
    return
  }
  
  // 上传文件
  try {
    const response: any = await apiUploadFile(file.raw)
    
    // 处理不同的响应格式
    if (response && response.code === 200) {
      const fileUrl = response.data?.fileUrl || response.data?.url || response.data
      
      // 添加到附件列表
      formData.attachments.push({
        id: 0, // 新上传的文件ID为0
        filename: file.name,
        filepath: fileUrl,
        filesize: file.raw.size,
        uploadTime: new Date()
      })
      ElMessage.success(`文件 "${file.name}" 上传成功`)
    } else if (response && typeof response === 'string') {
      // 如果响应直接是文件URL字符串
      formData.attachments.push({
        id: 0,
        filename: file.name,
        filepath: response,
        filesize: file.raw.size,
        uploadTime: new Date()
      })
      ElMessage.success(`文件 "${file.name}" 上传成功`)
    } else {
      ElMessage.error(`文件 "${file.name}" 上传失败: ${response?.message || '响应格式异常'}`)
    }
  } catch (error: any) {
    console.error('文件上传失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      ElMessage.error(`文件 "${file.name}" 上传失败: ${error.response.data?.message || error.message}`)
    } else if (error.request) {
      console.error('网络错误:', error.request)
      ElMessage.error(`文件 "${file.name}" 上传失败: 网络连接错误`)
    } else {
      ElMessage.error(`文件 "${file.name}" 上传失败: ${error.message}`)
    }
  }
}

// 批量上传
const handleBatchUpload = () => {
  ElMessage.info('请通过拖拽或点击选择文件进行上传')
}

// 测试上传服务连接
const testUploadService = async () => {
  try {
    console.log('测试上传服务连接...')
    // 创建一个简单的测试文件
    const testContent = 'test upload connection'
    const testFile = new File([testContent], 'test.txt', { type: 'text/plain' })
    
    const response = await apiUploadFile(testFile)
    console.log('上传服务测试成功:', response)
    return true
  } catch (error) {
    console.error('上传服务连接失败:', error)
    return false
  }
}

// 删除文件
const removeFile = (index: number) => {
  formData.attachments.splice(index, 1)
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}

// 格式化时间
const formatTime = (date: Date | string) => {
  const d = new Date(date)
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// =============== 销售订单相关方法 ===============

// 打开销售订单对话框
const openSalesOrderDialog = () => {
  if (!noSalesOrder.value) {
    salesOrderDialogVisible.value = true
    // 重置搜索条件和分页
    salesOrderSearch.orderNumber = ''
    salesOrderSearch.customerName = ''
    salesOrderSearch.orderDate = ''
    salesOrderSearch.status = ''
    salesOrderPagination.pageIndex = 1
    salesOrderPagination.pageSize = 5
    selectedSalesOrder.value = null
    // 加载数据
    loadSalesOrders()
  }
}

// 加载销售订单数据
const loadSalesOrders = async () => {
  salesOrderLoading.value = true
  try {
    const params = {
      PageIndex: salesOrderPagination.pageIndex,
      PageSize: salesOrderPagination.pageSize,
      OrderNumberOrSubject: salesOrderSearch.orderNumber || '',
      CustomerName: salesOrderSearch.customerName || '',
      StartDate: '',
      EndDate: '',
      OrderStatus: salesOrderSearch.status || ''
    }

    const response: any = await getSalesOrders(params)
    
    if (response && response.pageData) {
      salesOrderList.value = response.pageData?.map((item: any) => ({
        id: item.id,
        orderNo: item.salesOrderNumber,
        subject: item.orderSubject,
        customerName: item.customerName,
        orderDate: item.createTime ? new Date(item.createTime).toISOString().split('T')[0] : '',
        status: item.orderStatus,
        details: item.itemSummary || ''
      })) || []
      salesOrderTotal.value = response.totalCount || 0
    } else {
      ElMessage.error('加载销售订单数据失败')
      salesOrderList.value = []
      salesOrderTotal.value = 0
    }
  } catch (error: any) {
    console.error('加载销售订单失败:', error)
    ElMessage.error('加载销售订单失败，请稍后重试')
    salesOrderList.value = []
    salesOrderTotal.value = 0
  } finally {
    salesOrderLoading.value = false
  }
}

// 搜索销售订单
const searchSalesOrders = () => {
  salesOrderPagination.pageIndex = 1
  loadSalesOrders()
}

// 重置销售订单搜索
const resetSalesOrderSearch = () => {
  salesOrderSearch.orderNumber = ''
  salesOrderSearch.customerName = ''
  salesOrderSearch.orderDate = ''
  salesOrderSearch.status = ''
  salesOrderPagination.pageIndex = 1
  selectedSalesOrder.value = null
  loadSalesOrders()
}

// 处理销售订单选择变化
const handleSalesOrderSelectionChange = (selection: any[]) => {
  selectedSalesOrder.value = selection.length > 0 ? selection[0] : null
}

// 处理销售订单分页大小变化
const handleSalesOrderSizeChange = (val: number) => {
  salesOrderPagination.pageSize = val
  salesOrderPagination.pageIndex = 1
  loadSalesOrders()
}

// 处理销售订单分页变化
const handleSalesOrderCurrentChange = (val: number) => {
  salesOrderPagination.pageIndex = val
  loadSalesOrders()
}

// 确认选择销售订单
const confirmSelectSalesOrder = () => {
  if (selectedSalesOrder.value) {
    formData.salesOrderHold = selectedSalesOrder.value.id
    salesOrderDialogVisible.value = false
    ElMessage.success(`已选择销售订单：${selectedSalesOrder.value.orderNo}`)
  } else {
    ElMessage.warning('请选择一个销售订单')
  }
}

// 处理不指定销售订单的变化
const handleNoSalesOrderChange = (value: boolean) => {
  if (value) {
    formData.salesOrderHold = 0
    ElMessage.info('已设置为不指定销售订单')
  }
}


</script>

<style scoped>
.edit-internal-production-container {
  background: #f5f5f5;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.form-header {
  background: white;
  border-bottom: 1px solid #e6e6e6;
  height: 80px !important;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-shrink: 0;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.form-main {
  background: white;
  margin: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 30px;
  flex: 1;
  overflow-y: auto;
  max-height: calc(100vh - 120px);
}

.form-container {
  width: 100%;
}

.form-section {
  margin-bottom: 40px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

.form-content {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
}

.table-operations {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.form-table {
  width: 100%;
}

.empty-table {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
  background: white;
  border-radius: 8px;
  margin-top: 10px;
}

.attachment-section {
  display: flex;
  gap: 20px;
}

.attachment-left {
  flex: 1;
}

.attachment-right {
  flex: 1;
}

.uploaded-files {
  background: white;
  border-radius: 8px;
  border: 1px solid #e6e6e6;
}

.files-title {
  padding: 15px 20px;
  border-bottom: 1px solid #e6e6e6;
  font-weight: 600;
  color: #303133;
}

.file-list {
  max-height: 200px;
  overflow-y: auto;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.file-item:last-child {
  border-bottom: none;
}

.file-item .el-icon {
  font-size: 18px;
  color: #409eff;
}

.file-name {
  flex: 1;
  color: #303133;
  font-weight: 500;
}

.file-size {
  color: #909399;
  font-size: 12px;
}

.upload-time {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}

.upload-area {
  width: 100%;
}

.upload-content {
  padding: 40px 20px;
  text-align: center;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-hint {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}

.upload-buttons {
  margin-top: 15px;
}

.item-search {
  margin-bottom: 20px;
}

.item-search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.dialog-pagination {
  margin-top: 20px;
  text-align: center;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: center;
}

:deep(.el-dialog__body) {
  padding: 10px 20px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #e6e6e6;
  padding: 15px 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #e6e6e6;
  padding: 15px 20px;
}

/* 主滚动区域的滚动条样式 */
.form-main::-webkit-scrollbar {
  width: 8px;
}

.form-main::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.form-main::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.form-main::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style> 